#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
	if(argc != 3) {
		printf("Usage : ./a.out ip port");
		return -1;
	}

	int cli_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(cli_fd < 0) {
		perror("socket create");
		return -1;
	}

	struct sockaddr_in serv_addr;
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(atoi(argv[2]));
	serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
	socklen_t len = sizeof(struct sockaddr_in);

	//不建议手动绑定， 由操作系统随机绑定
	int ret = connect(cli_fd, (struct sockaddr*)&serv_addr, len);
	if(ret < 0) {
		perror("connect");
		return -1;
	}

	while(1) {
		char buff[1024] = {0};
		printf("input : ");
		fflush(stdout);
		scanf("%s", buff);
		send(cli_fd, buff, strlen(buff), 0);

		char temp[1024] = {0};
		int ret = recv(cli_fd, temp, 1023, 0);
		if(ret < 0) {
			perror("recv");
			continue;
		}
		printf("serv say : %s\n" , temp);
	}
	close(cli_fd);
	return 0;
}
